package com.yaodian100.ec.creditcard.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.entity.Option;
import com.yaodian100.ec.common.web.AbstractAction;
import com.yaodian100.ec.creditcard.entity.CreditcardSetting;
import com.yaodian100.ec.creditcard.service.CreditcardSettingService;

public class CreditcardSettingAction extends AbstractAction {
	
	private static final long serialVersionUID = 7303503821221886579L;

	private final Logger logger = LoggerFactory.getLogger(CreditcardSettingAction.class);
	
	private CreditcardSettingService creditcardSettingService;
	private DomainService<Menu> menuService;
	
	private Menu periodMenu;
	private Menu bankMenu;
	private CreditcardSetting creditcardSetting;
	
	// 搜寻条件
	private String paraName;
	
	private List<CreditcardSetting> campaignList;
	
	// 
	private String bankId;
	private String bankCode;
	/**
	 * 信用卡银行名称
	 */
	private String creditcardName;
	/**
	 * 信用卡支援期数
	 */
	private String[] periods;
	/**
	 * 信用卡手续费
	 */
	private String[] fees;
	/**
	 * 信用卡交易金额下限
	 */
	private String[] downLimits;
	/**
	 * 信用卡交易金额上限
	 */
	private String[] upLimits;
	/*
	public String list() {
		return "list";
	}

	public String search() {
		try {
			CommonCriteria cri = new CommonCriteria();
			if (StringUtils.isNotBlank(paraName)) {
				cri.addRlike("creditcardName", paraName);
			}
			cri.addEq("delete", false);
			
			int entitySize = creditcardSettingService.getListSize(cri).intValue();
			getPager().setTotalSize(entitySize);
			campaignList = creditcardSettingService.getList(getPager().getCurrentPage() * getPager().getPageRecord(), 
					getPager().getPageRecord(), cri, new String[] { "id desc" });
		} catch (Exception e) {
			addActionError("搜寻失败：" + e.getMessage());
			e.printStackTrace();
		}
		return "list";
	}
	
	public String add() {
		bankId = "";
		
		initVariables();
		return "edit";
	}
	*/
	public String edit() {
		initVariables();
		
		if( !StringUtils.isBlank(bankCode) ) {
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("bankCode", bankCode);
			List<CreditcardSetting> list = creditcardSettingService.getList(0, -1, criteria, new String[] {});
			if( list.size() > 0 ) {
				creditcardSetting = creditcardSettingService.get(list.get(0).getId());
				
				List<String> periodList = creditcardSetting.getPeriods();
				Map<String, Float> feeMap = creditcardSetting.getPeriodFees();
				Map<String, List<Float>> amountMap = creditcardSetting.getAmountLimits();
				
				bankId = "" + creditcardSetting.getId();
				bankCode = creditcardSetting.getBankCode();
				creditcardName = creditcardSetting.getCreditcardName();
				
				Iterator<String> iter = periodMenu.getOptions().keySet().iterator();
				int i = 0;
				while(iter.hasNext()) {
					String k = iter.next().toString();
					
					boolean isExist = false;
					for(int j = 0; j < periodList.size(); j++) {
						if( k.equals(periodList.get(j)) ) {
							isExist = true;
							
							periods[i] = periodList.get(j);
							fees[i] = feeMap.get(k).toString();
							downLimits[i] = amountMap.get(k).get(0).toString();
							upLimits[i] = amountMap.get(k).get(1).toString();
							
							break;
						}
					}
					
					if( !isExist ) {
						periods[i] = "";
						fees[i] = "";
						downLimits[i] = "";
						upLimits[i] = "";
					}
					
					i++;
				}
			} else {
				creditcardName = bankMenu.getOptions().get(bankCode).getName();
			}
			
		}
		
		return "edit";
	}
	
	public String save() {
		try {
			if(creditcardValidate()) {
				if(StringUtils.isBlank(bankId)) 
					creditcardSetting = new CreditcardSetting();
				else 
					creditcardSetting = creditcardSettingService.get(new Long(bankId));
				
				creditcardSetting.setBankCode(bankCode);
				creditcardSetting.setCreditcardName(creditcardName);
				
				JSONArray periodJA = new JSONArray(toList(periods));
				creditcardSetting.setCreditcardPeriod(periodJA.toString());
				
				Map<String, JSONArray> map = new HashMap<String, JSONArray>();
				for(int i = 0; i < periods.length; i++) {
					String period = periods[i];
					if(!StringUtils.isBlank(period)) {
						List<String> list = new ArrayList<String>();
						list.add(fees[i]);
						list.add(downLimits[i]);
						list.add(upLimits[i]);
						map.put(period, new JSONArray(list));
					}
				}
				JSONObject jo = new JSONObject(map);
				creditcardSetting.setCreditcardDetail(jo.toString());
				
				boolean isSave = true;
				try {
					if (StringUtils.isBlank(bankId)) {
						creditcardSetting = creditcardSettingService.save(creditcardSetting);
					} else {
						creditcardSetting = creditcardSettingService.update(creditcardSetting);
					}
				} catch (Exception e) {
					isSave = false;
				}
				
				if( isSave ) {
					bankId = creditcardSetting.getId() + "";
					addActionMessage("储存成功");
					return edit();
				} else {
					return "edit";
				}
			}
		} catch (Exception e) {
			addActionError("储存失败：" + e.getMessage());
			e.printStackTrace();
		}
		
		return "edit";
	}
	/*
	public String delete() {
		try {
			if( StringUtils.isBlank(bankId) ) {
				addActionError("信用卡活动不存在");
				return search();
			}
			
			creditcardSettingService.delete(creditcardSettingService.get(new Long(bankId).longValue()));
		} catch (Exception e) {
			addActionError("删除失败：" + e.getMessage());
			e.printStackTrace();
		}
		return search();
	}
	*/
	boolean creditcardValidate() {
		if(StringUtils.isBlank(creditcardName)) {
			addFieldError("creditcardName", "请输入信用卡银行名称");
		}
		
		boolean isPeriodBlank = true;
		for(int i = 0; i < periods.length; i ++) {
			String period = periods[i];
			if(!StringUtils.isBlank(period)) {
				isPeriodBlank = false;
				
				if(StringUtils.isBlank(fees[i])) {
					addFieldError("fees_" + (i+1), "请输入" + period + "期的会员自付手续费");
				}
				
				if(StringUtils.isBlank(downLimits[i])) {
					addFieldError("downLimits_" + (i+1), "请输入" + period + "期的交易金额下限");
				}
				
				if(StringUtils.isBlank(upLimits[i])) {
					addFieldError("upLimits_" + (i+1), "请输入" + period + "期的交易金额上限");
				}
				
				if( !StringUtils.isBlank(downLimits[i]) && !StringUtils.isBlank(upLimits[i]) ) {
					if( NumberUtils.toFloat(downLimits[i]) > NumberUtils.toFloat(upLimits[i]) ) {
						addFieldError("detail", period + "期的交易下限金额要小于上限金额");
					}
				}
			}
		}
		
		if(isPeriodBlank) {
			addFieldError("periods", "请选择信用卡支持期数");
		}
		
		if (getFieldErrors().isEmpty()) {
			return true;
		} else {
			return false;
		}
	}
	
	List<String> toList(String[] args) {
		List<String> list = new ArrayList<String>();
		
		if(args.length > 0) {
			for(String arg : args) {
				if(!StringUtils.isBlank(arg))
					list.add(arg);
			}
		}
		
		return list;
	}
	
	void initVariables() {
		bankId = "";
		creditcardName = "";
		
		periods = new String[periodMenu.getOptions().size()];
		fees = new String[periodMenu.getOptions().size()];
		downLimits = new String[periodMenu.getOptions().size()];
		upLimits = new String[periodMenu.getOptions().size()];
		
		creditcardSetting = new CreditcardSetting();
	}
	
	@Override
	public void prepare() throws Exception {
		clearErrorsAndMessages();
		
		if(periodMenu == null)
			periodMenu = menuService.get("Creditcard.period");
		
		if(bankMenu == null)
			bankMenu = menuService.get("Creditcard.bank");
	}
	
	// Getters & Setters
	public CreditcardSettingService getCreditcardSettingService() {
		return creditcardSettingService;
	}

	public void setCreditcardSettingService(
			CreditcardSettingService creditcardSettingService) {
		this.creditcardSettingService = creditcardSettingService;
	}

	public String getCreditcardName() {
		return creditcardName;
	}

	public void setCreditcardName(String creditcardName) {
		this.creditcardName = creditcardName;
	}

	public String[] getPeriods() {
		return periods;
	}

	public void setPeriods(String[] periods) {
		this.periods = periods;
	}

	public String[] getFees() {
		return fees;
	}

	public void setFees(String[] fees) {
		this.fees = fees;
	}

	public String[] getDownLimits() {
		return downLimits;
	}

	public void setDownLimits(String[] downLimits) {
		this.downLimits = downLimits;
	}

	public String[] getUpLimits() {
		return upLimits;
	}

	public void setUpLimits(String[] upLimits) {
		this.upLimits = upLimits;
	}

	public String getBankId() {
		return bankId;
	}

	public void setBankId(String bankId) {
		this.bankId = bankId;
	}

	public DomainService<Menu> getMenuService() {
		return menuService;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public Menu getPeriodMenu() {
		return periodMenu;
	}

	public void setPeriodMenu(Menu periodMenu) {
		this.periodMenu = periodMenu;
	}

	public CreditcardSetting getCreditcardSetting() {
		return creditcardSetting;
	}

	public void setCreditcardSetting(CreditcardSetting creditcardSetting) {
		this.creditcardSetting = creditcardSetting;
	}

	public String getParaName() {
		return paraName;
	}

	public void setParaName(String paraName) {
		this.paraName = paraName;
	}

	public List<CreditcardSetting> getCampaignList() {
		return campaignList;
	}

	public void setCampaignList(List<CreditcardSetting> campaignList) {
		this.campaignList = campaignList;
	}

	public Menu getBankMenu() {
		return bankMenu;
	}

	public void setBankMenu(Menu bankMenu) {
		this.bankMenu = bankMenu;
	}

	public String getBankCode() {
		return bankCode;
	}

	public void setBankCode(String bankCode) {
		this.bankCode = bankCode;
	}

}
